﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AtomMonitor
{
    internal class Program
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        public static extern uint GlobalGetAtomNameW(ushort nAtom, StringBuilder lpBuffer, int nSize);
        [DllImport("user32.dll")]
        private static extern short GetAsyncKeyState(Keys vKey);
        public static void MonitorAtomTable()
        {
            const int USER_ATOM_START = 1;
            const int USER_ATOM_END = 0xFFFF;
            StringBuilder buffer = new StringBuilder(256);
            int usercount = 0;
            int totalcount= 0;

            for (ushort atom = USER_ATOM_START; atom <= USER_ATOM_END; atom++)
            {
                uint len = GlobalGetAtomNameW(atom, buffer, buffer.Capacity);
                if (len > 0)
                {
                    string atomName = buffer.ToString();
                    Console.WriteLine($"原子 ID: {atom}, 名称: {atomName}");
                    totalcount++;
                }
                if (atom >= 0xC000)
                {
                    if (len > 0)
                        usercount++;
                }
                if (atom == 65535)
                {
                    break;
                }
            }
            Console.WriteLine($"用户原子数：{usercount} 总原子数: {totalcount}（接近65k可能耗尽）");
        }
        static void Main(string[] args)
        {
            //while (Console.ReadKey().Key == ConsoleKey.Enter)
            //{
            //    MonitorAtomTable();
            //}
            bool conti = true;
            DateTime dt = DateTime.Now;
            while (true)
            {

                if ((GetAsyncKeyState(Keys.Escape) & 0x8000) != 0)
                {
                    break;
                }
                if ((GetAsyncKeyState(Keys.Back) & 0x8000) != 0)
                {
                    conti = false;
                }
                if (conti)
                {
                    if ((GetAsyncKeyState(Keys.Enter) & 0x8000) != 0)
                    {
                        conti = true;
                    }
                    if ((DateTime.Now - dt).TotalMilliseconds >= 5000 || ((GetAsyncKeyState(Keys.Enter) & 0x8000) != 0))
                    {
                        dt = DateTime.Now;
                        MonitorAtomTable();

                    }
                }

            }
        }
    }
}
